package com.cloudkinto.service.firstvesselorder.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.OrderCodeUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.fbaproduct.FbaProductService;
import com.cloudkinto.service.fbaproduct.vo.FbaProductDetailRes;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.finance.CostRecordService;
import com.cloudkinto.service.firstvesselorder.FirstVesselOrderService;
import com.cloudkinto.service.firstvesselorder.vo.*;
import com.cloudkinto.service.headercontainer.HeaderContainerService;
import com.cloudkinto.service.storage.StorageService;
import com.cloudkinto.service.tailtrucks.TailTrucksService;
import com.cloudkinto.service.user.WxUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-09-16
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class FirstVesselOrderServiceImpl extends ServiceImpl<FirstVesselOrderDao, FirstVesselOrderDo> implements FirstVesselOrderService {
    @Autowired
    private FirstVesselOrderDao dao;
    @Autowired
    private FirstVesselOrderPackageDao firstVesselOrderPackageDao;
    @Autowired
    private FirstVesselOrderProductDao firstVesselOrderProductDao;
    @Autowired
    private StorageService storageService;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;
    @Autowired
    private FbaStorageDao fbaStorageDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private FbaProductService fbaProductService;
    @Autowired
    private FbaDimensDao fbaDimensDao;
    @Autowired
    private FbaShipPriceDao fbaShipPriceDao;
    @Autowired
    private CostRecordService mCostService;
    @Autowired
    private FirstVesselOrderPriceDao firstVesselOrderPriceDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private ThreadPoolTaskExecutor executor;
    @Autowired
    private HeaderContainerOrderDao headerContainerOrderDao;
    @Autowired
    private HeaderContainerService headerContainerService;
    @Autowired
    private TailTrucksService tailTrucksService;
    @Autowired
    private TailTrucksDetailDao tailTrucksDetailDao;

    @Override
    public SingleResult addInit() {
        Map result = new HashMap();

        List<Map> storageList = new ArrayList<>();
        LambdaQueryWrapper<StorageDo> storageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storageDoLambdaQueryWrapper.eq(StorageDo::getCountryType, 2);
        List<StorageDo> storageDos = storageService.getBaseMapper().selectList(storageDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(storageDos)) {
            for (StorageDo storageDo : storageDos) {
                Map map = new HashMap();
                map.put("id", storageDo.getId());
                map.put("value", storageDo.getStorageName());
                storageList.add(map);
            }
        }
        result.put("storageList", storageList);

        //运输方式
        List<Map> transportTypeList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.transportType);
        List<DicBusinessItemDo> transportType = dicBusinessItemDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(transportType)) {
            transportType.forEach(e -> {
                Map map = new HashMap();
                map.put("id", e.getId());
                map.put("value", e.getDicItemValue());
                transportTypeList.add(map);
            });
        }
        result.put("transportTypeList", transportTypeList);

        //状态
        List<Map> statusList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> statusWrapper = new LambdaQueryWrapper<>();
        statusWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.seaTransportationStatus);
        List<DicBusinessItemDo> statusType = dicBusinessItemDao.selectList(statusWrapper);
        if (!CollectionUtils.isEmpty(statusType)) {
            statusType.forEach(e -> {
                Map map = new HashMap();
                map.put("id", e.getId());
                map.put("value", e.getDicItemValue());
                statusList.add(map);
            });
        }
        result.put("statusList", statusList);

        //fbaStorage
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.orderByAsc("fba_code");
        List<FbaStorageDo> fbaStorageDos = fbaStorageDao.selectList(wrapper1);
        List<Map> fbaStorageList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(fbaStorageDos)) {
            fbaStorageDos.forEach(fbaStorageDo -> {
                Map fbaMap = new HashMap();
                fbaMap.put("id", fbaStorageDo.getId());
                fbaMap.put("code", fbaStorageDo.getFbaCode());
                fbaMap.put("name", fbaStorageDo.getFbaName());
                fbaMap.put("address", fbaStorageDo.getAddress());
                fbaMap.put("postCode", fbaStorageDo.getPostCode());
                fbaMap.put("tel", fbaStorageDo.getTelPhone());
                fbaStorageList.add(fbaMap);
            });
        }
        result.put("fbaStorageList", fbaStorageList);

        //报关方式
        List<Map> customsTypeList = new ArrayList<>();
        Map map = new HashMap();
        map.put("id", 1);
        map.put("value", "退税报关");
        customsTypeList.add(map);
        map = new HashMap();
        map.put("id", 2);
        map.put("value", "非退税");
        customsTypeList.add(map);
        result.put("customsTypeList", customsTypeList);

        //配送方式
        List<Map> distributionTypeList = new ArrayList<>();
        map = new HashMap();
        map.put("id", 1);
        map.put("value", "上门取件");
        distributionTypeList.add(map);
        map = new HashMap();
        map.put("id", 2);
        map.put("value", "送货到仓");
        distributionTypeList.add(map);
        result.put("distributionTypeList", distributionTypeList);


        return SingleResult.success(result);
    }

    @Override
    public FirstVesselOrderAddReq add(FirstVesselOrderAddReq req, Long userId, Long companyId) {
        if (companyId == null) {
            throw new BizException(SysConstant.Error_Company);
        }
        addCheck(req);
        FirstVesselOrderDo entityDo = new FirstVesselOrderDo();
        fileService.uploadFile(req.getCommodityFileId());
        fileService.uploadFile(req.getCustomsClearanceFileId());
        fileService.uploadFile(req.getDeclarationInformationFileId());
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setCompanyId(companyId);
        entityDo.setPickDate(TimeUtils.parseDate(req.getPickDate()));
        entityDo.setDeliverTime(TimeUtils.parseDate(req.getDeliverTime()));
        entityDo.setIsLabelling(SysConstant.DELETE_FLAG_FALSE);
        entityDo.setResultStatus(getResultStatus(req.getStatus()));
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        String firstVesselNumber = OrderCodeUtil.getFirstVesselNumber(entityDo.getId());
        entityDo.setOrderNumber(firstVesselNumber);
        dao.updateById(entityDo);

        req.getPackageList().forEach(packageReq -> {
            FirstVesselOrderPackageDo packageDo = new FirstVesselOrderPackageDo();
            BeanUtils.copyProperties(packageReq, packageDo);
            packageDo.setOrderId(entityDo.getId());
            packageDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            firstVesselOrderPackageDao.insert(packageDo);

            packageReq.getProductList().forEach(productReq -> {
                FirstVesselOrderProductDo productDo = new FirstVesselOrderProductDo();
                BeanUtils.copyProperties(productReq, productDo);
                productDo.setOrderId(entityDo.getId());
                productDo.setPackageId(packageDo.getId());
                productDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                firstVesselOrderProductDao.insert(productDo);
            });
        });

//        handlerFee(entityDo);
        return req;
    }

    //新增校验
    private void addCheck(FirstVesselOrderAddReq req) {
        if (req.getIsCloudkintoExport() == 1 && StringUtils.isBlank(req.getDutyParagraph())) {
            throw new BizException(SysConstant.FirstVessel_Check_DutyParagraph);
        }
    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(FirstVesselOrderDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }


    @Override
    public SingleResult updateInit(Long id) {
        Map result = (Map) addInit().getData();
        result.put("detail", detail(id));
        return SingleResult.success(result);
    }

    @Override
    public SingleResult orderProductDetail(Long id) {
        List<FirstVesselOrderPackageDetailRes> packageDetailResList = new ArrayList<>();

        LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, id);
        List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(packageDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
            firstVesselOrderPackageDos.forEach(packageDo -> {
                FirstVesselOrderPackageDetailRes packageDetailRes = new FirstVesselOrderPackageDetailRes();
                BeanUtils.copyProperties(packageDo, packageDetailRes);
                packageDetailRes.setWeight(packageDo.getWeight() * packageDo.getCount());

                List<FbaProductDetailRes> productDetailResList = new ArrayList<>();
                LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getPackageId, packageDo.getId());
                List<FirstVesselOrderProductDo> firstVesselOrderProductDos = firstVesselOrderProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(firstVesselOrderProductDos)) {
                    firstVesselOrderProductDos.forEach(productDo -> {
                        FbaProductDetailRes productDetailRes = fbaProductService.detail(productDo.getProductId());
                        productDetailRes.setCount(productDo.getCount());
                        productDetailResList.add(productDetailRes);
                    });
                }

                packageDetailRes.setProductList(productDetailResList);
                packageDetailResList.add(packageDetailRes);
            });
        }
        return SingleResult.success(packageDetailResList);
    }

    @Override
    public FirstVesselOrderUpdateReq update(FirstVesselOrderUpdateReq req, Long userId) {
        FirstVesselOrderDo entityDo = dao.selectById(req.getId());

        if (req.getCommodityFileId() != null && !req.getCommodityFileId().equals(entityDo.getCommodityFileId())) {
            fileService.deleteFile(entityDo.getCommodityFileId());
            fileService.uploadFile2(req.getCommodityFileId(), entityDo.getCommodityFileId());
        }
        if (req.getCustomsClearanceFileId() != null && !req.getCustomsClearanceFileId().equals(entityDo.getCustomsClearanceFileId())) {
            fileService.deleteFile(entityDo.getCustomsClearanceFileId());
            fileService.uploadFile2(req.getCustomsClearanceFileId(), entityDo.getCustomsClearanceFileId());
        }
        if (req.getDeclarationInformationFileId() != null && !req.getDeclarationInformationFileId().equals(entityDo.getDeclarationInformationFileId())) {
            fileService.deleteFile(entityDo.getDeclarationInformationFileId());
            fileService.uploadFile2(req.getDeclarationInformationFileId(), entityDo.getDeclarationInformationFileId());
        }

        req.setStatus(entityDo.getStatus());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);

        LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, req.getId());
        firstVesselOrderPackageDao.delete(packageDoLambdaQueryWrapper);

        LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getOrderId, req.getId());
        firstVesselOrderProductDao.delete(productDoLambdaQueryWrapper);

        req.getPackageList().forEach(packageReq -> {
            FirstVesselOrderPackageDo packageDo = new FirstVesselOrderPackageDo();
            BeanUtils.copyProperties(packageReq, packageDo);
            packageDo.setOrderId(entityDo.getId());
            packageDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            firstVesselOrderPackageDao.insert(packageDo);

            packageReq.getProductList().forEach(productReq -> {
                FirstVesselOrderProductDo productDo = new FirstVesselOrderProductDo();
                BeanUtils.copyProperties(productReq, productDo);
                productDo.setOrderId(entityDo.getId());
                productDo.setPackageId(packageDo.getId());
                productDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                firstVesselOrderProductDao.insert(productDo);
            });
        });


        //编辑拼柜的po号
        executor.execute(() -> {
            LambdaQueryWrapper<HeaderContainerOrderDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(HeaderContainerOrderDo::getFirstVesselOrderId, req.getId());
            List<HeaderContainerOrderDo> headerContainerOrderDos = headerContainerOrderDao.selectList(wrapper);
            if (!CollectionUtils.isEmpty(headerContainerOrderDos)) {
                headerContainerService.updatePoNumberHandler(headerContainerOrderDos.get(0).getHeaderContainerId());
            }

            LambdaQueryWrapper<TailTrucksDetailDo> trucksDetailWrapper = new LambdaQueryWrapper<>();
            trucksDetailWrapper.eq(TailTrucksDetailDo::getOrderId, req.getId()).eq(TailTrucksDetailDo::getType, 1);
            List<TailTrucksDetailDo> tailTrucksDetailDos = tailTrucksDetailDao.selectList(trucksDetailWrapper);
            if (!CollectionUtils.isEmpty(tailTrucksDetailDos)) {
                tailTrucksService.updatePoNumberHandler(tailTrucksDetailDos.get(0).getTrucksId());
            }
        });

        return req;
    }

    @Override
    public void updateStatus(FirstVesselUpdateStatusReq req, Long userId) {
        //判断是否要扣除 头程费 或尾程费的标志
        boolean isDeHeadFee = false;
        boolean isDeTailFee = false;

        FirstVesselOrderDo firstVesselOrderDo = dao.selectById(req.getId());
        if (firstVesselOrderDo.getStatus() < DicBusinessItemConstant.seaStorageHandler) {
            isDeHeadFee = true;
        }
        if (firstVesselOrderDo.getStatus() < DicBusinessItemConstant.seaDelivery) {
            isDeTailFee = true;
        }

        firstVesselOrderDo.setStatus(req.getStatus());
        firstVesselOrderDo.setUpdateBy(userId);
        firstVesselOrderDo.setUpdateTime(new Date());
        firstVesselOrderDo.setResultStatus(getResultStatus(req.getStatus()));
        dao.updateById(firstVesselOrderDo);

        //如果是已派送 计算费用
        if (req.getStatus().equals(DicBusinessItemConstant.seaDelivery)) {
            handlerFee(firstVesselOrderDo);
        }

        //头程扣费
        if (isDeHeadFee && req.getStatus().equals(DicBusinessItemConstant.seaStorageHandler)) {
            double fee = 0;
            LambdaQueryWrapper<FirstVesselOrderPriceDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FirstVesselOrderPriceDo::getOrderId, req.getId());
            List<FirstVesselOrderPriceDo> firstVesselOrderPriceDos = firstVesselOrderPriceDao.selectList(wrapper);
            if (!CollectionUtils.isEmpty(firstVesselOrderPriceDos)) {
                for (FirstVesselOrderPriceDo firstVesselOrderPriceDo : firstVesselOrderPriceDos) {
                    fee += firstVesselOrderPriceDo.getPrice();
                }
            }
            mCostService.add(0, firstVesselOrderDo.getOrderNumber() + "头程订单头程费", fee, null, firstVesselOrderDo.getCompanyId(), firstVesselOrderDo.getId());
        }

        //尾程扣费
        if (isDeTailFee && req.getStatus().equals(DicBusinessItemConstant.seaDelivery)) {
            double totalFee = firstVesselOrderDo.getDeliveryFee();
            mCostService.add(0, firstVesselOrderDo.getOrderNumber() + "头程订单尾程费", totalFee, null, firstVesselOrderDo.getCompanyId(), firstVesselOrderDo.getId());
        }

        //异步推送微信公众号
        executor.execute(() -> {
            wxUserService.firstVessel(firstVesselOrderDo);
        });


    }

    @Override
    public void uploadImages(firstVesselUploadImagesReq req) {
        FirstVesselOrderDo firstVesselOrderDo = dao.selectById(req.getId());

        StringBuilder sb = new StringBuilder("");
        for (Long fileId : req.getFileIds()) {
            sb.append(fileId + ";");
        }
        if (req.getType() == 1) {
            if (StringUtils.isNotBlank(firstVesselOrderDo.getInternalImage())) {
                String[] split = firstVesselOrderDo.getInternalImage().split(";");
                for (String s : split) {
                    fileService.deleteFile(Long.parseLong(s));
                }
            }
            firstVesselOrderDo.setInternalImage(sb.toString());
        } else {
            if (StringUtils.isNotBlank(firstVesselOrderDo.getForeignImage())) {
                String[] split = firstVesselOrderDo.getForeignImage().split(";");
                for (String s : split) {
                    fileService.deleteFile(Long.parseLong(s));
                }
            }
            firstVesselOrderDo.setForeignImage(sb.toString());
        }
        for (Long fileId : req.getFileIds()) {
            fileService.uploadFile(fileId);
        }
        dao.updateById(firstVesselOrderDo);
    }

    @Override
    public SingleResult updateStatusInit() {
        //状态
        return SingleResult.success(dicBusinessItemService.getDicItemList(DicBusinessConstant.seaTransportationStatus));
    }

    @Override
    public void orderBack(FirstVesselBackReq req, Long userId) {
        FirstVesselOrderDo firstVesselOrderDo = dao.selectById(req.getId());
        firstVesselOrderDo.setStatus(DicBusinessItemConstant.seaUnsubmit);
        firstVesselOrderDo.setRemark(req.getRemark());
        firstVesselOrderDo.setUpdateBy(userId);
        firstVesselOrderDo.setUpdateTime(new Date());
        firstVesselOrderDo.setResultStatus(getResultStatus(DicBusinessItemConstant.seaBack));
        dao.updateById(firstVesselOrderDo);
    }

    @Override
    public void updateLabellingStatus(FirstVesselUpdateLabellingReq req) {
        FirstVesselOrderDo firstVesselOrderDo = dao.selectById(req.getId());
        firstVesselOrderDo.setIsLabelling(req.getIsLabelling());
        dao.updateById(firstVesselOrderDo);
    }

    //根据status 获取resultStatus
    private Integer getResultStatus(Long status) {
        Integer resultStatus = null;
        if (status >= DicBusinessItemConstant.seaSubmit && status <= DicBusinessItemConstant.seaDispatchShip) {
            resultStatus = 1;
        } else if (status == DicBusinessItemConstant.seaDelivery) {
            resultStatus = 2;
        } else if (status == DicBusinessItemConstant.seaBack) {
            resultStatus = 3;
        }
        return resultStatus;
    }

    @Override
    public void uploadCartonabel(FirstVesselUploadFileReq req, Long userId) {
        FirstVesselOrderDo entityDo = dao.selectById(req.getId());
        if (req.getFileId() != null) {
            fileService.deleteFile(entityDo.getCommodityFileId());
            entityDo.setCommodityFileId(req.getFileId());
            fileService.uploadFile2(req.getFileId(), entityDo.getCommodityFileId());
            dao.updateById(entityDo);
        }
    }

    @Override
    public SingleResult downloadDeclaration(Long id) {
        FirstVesselOrderDo entityDo = dao.selectById(id);
        if (entityDo.getDeclarationInformationFileId() != null) {
            return SingleResult.success(fileService.getFilePath(entityDo.getDeclarationInformationFileId()));
        }
        return SingleResult.success(null);
    }

    @Override
    public void reDelivery(Long id, Long userId) {
        FirstVesselOrderDo entityDo = dao.selectById(id);
        entityDo.setStatus(DicBusinessItemConstant.seaDelivery);
        entityDo.setResultStatus(getResultStatus(DicBusinessItemConstant.seaDelivery));
        dao.updateById(entityDo);
    }

    @Override
    public void uploadDeclaration(FirstVesselUploadFileReq req, Long userId) {
        FirstVesselOrderDo entityDo = dao.selectById(req.getId());
        if (req.getFileId() != null) {
            fileService.deleteFile(entityDo.getDeclarationInformationFileId());
            entityDo.setDeclarationInformationFileId(req.getFileId());
            fileService.uploadFile2(req.getFileId(), entityDo.getDeclarationInformationFileId());
            dao.updateById(entityDo);
        }
    }

    @Override
    public void uploadCertificate(FirstVesselUploadFileReq req, Long userId) {
        FirstVesselOrderDo entityDo = dao.selectById(req.getId());
        if (req.getFileId() != null) {
            fileService.deleteFile(entityDo.getDeclarationCertificateFileId());
            entityDo.setDeclarationCertificateFileId(req.getFileId());
            fileService.uploadFile2(req.getFileId(), entityDo.getDeclarationCertificateFileId());
            dao.updateById(entityDo);
        }
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(FirstVesselOrderDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }


    @Override
    public int delete(Long id, Long userId) {

        FirstVesselOrderDo entityDo = dao.selectById(id);
        if (entityDo.getIsContainer() == SysConstant.DELETE_FLAG_TRUE) {
            throw new BizException(SysConstant.FirstVessel_Delete_Error);
        }
        handlerDeleteBefore(entityDo, userId);
        dao.deleteById(id);

        LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, entityDo.getId());
        firstVesselOrderPackageDao.delete(packageDoLambdaQueryWrapper);

        LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getOrderId, entityDo.getId());
        firstVesselOrderProductDao.delete(productDoLambdaQueryWrapper);

        fileService.deleteFile(entityDo.getCommodityFileId());
        fileService.deleteFile(entityDo.getDeclarationInformationFileId());
        fileService.deleteFile(entityDo.getCustomsClearanceFileId());
        return 1;
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(FirstVesselOrderDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public FirstVesselOrderDetailRes detail(Long id) {
        FirstVesselOrderDo entityDo = dao.selectById(id);
        FirstVesselOrderDetailRes res = new FirstVesselOrderDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        res.setCustomsClearanceFileUrl(fileService.getFilePath(entityDo.getCustomsClearanceFileId()));
        res.setDeclarationInformationFileUrl(fileService.getFilePath(entityDo.getDeclarationInformationFileId()));
        res.setCommodityFileUrl(fileService.getFilePath(entityDo.getCommodityFileId()));
        res.setDeclarationCertificateFileUrl(fileService.getFilePath(entityDo.getDeclarationCertificateFileId()));
        res.setIsLabelling(entityDo.getIsLabelling() == 1 ? "是" : "否");
        if (StringUtils.isNotBlank(entityDo.getInternalImage())) {
            List<String> internalImageList = new ArrayList<>();
            String[] split = entityDo.getInternalImage().split(";");
            for (String s : split) {
                internalImageList.add(fileService.getFilePath(Long.parseLong(s)));
            }
            res.setInternalImageList(internalImageList);
        }
        if (StringUtils.isNotBlank(entityDo.getForeignImage())) {
            List<String> foreignImageList = new ArrayList<>();
            String[] split = entityDo.getForeignImage().split(";");
            for (String s : split) {
                foreignImageList.add(fileService.getFilePath(Long.parseLong(s)));
            }
            res.setForeignImageList(foreignImageList);
        }

        DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(entityDo.getStatus());
        if (businessItemDo != null) {
            res.setStatus(businessItemDo.getDicItemValue());
        }
        res.setResultStatus(getResultStatusStr(entityDo.getResultStatus()));

        res.setResultStatus(getResultStatusStr(entityDo.getResultStatus()));

        StorageDo storageDo = storageDao.selectById(entityDo.getStorageId());
        if (storageDo != null) {
            res.setStorageName(storageDo.getStorageName());
        }

        FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(entityDo.getFbaStorageId());
        if (fbaStorageDo != null) {
            res.setFbaStorageName(fbaStorageDo.getFbaName());
        }

        DicBusinessItemDo logisticsType = dicBusinessItemDao.selectById(entityDo.getLogisticsType());
        if (logisticsType != null) {
            res.setLogisticsTypeName(logisticsType.getDicItemValue());
        }
        res.setIsCloudkintoExportName(entityDo.getIsCloudkintoExport() == 1 ? "是" : "否");
        res.setCustomsTypeName(entityDo.getCustomsType() == 1 ? "报关退税" : "非退税");
        res.setIsPurchaseOfInsuranceName(entityDo.getIsPurchaseOfInsurance() == 1 ? "是" : "否");
        res.setDistributionTypeName(entityDo.getDistributionType() == 1 ? "上门取件" : "送货到仓");

        List<FirstVesselOrderPackageDetailRes> packageDetailResList = new ArrayList<>();

        LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, id);
        List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(packageDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
            firstVesselOrderPackageDos.forEach(packageDo -> {
                FirstVesselOrderPackageDetailRes packageDetailRes = new FirstVesselOrderPackageDetailRes();
                BeanUtils.copyProperties(packageDo, packageDetailRes);
                packageDetailRes.setWeight(packageDo.getWeight() * packageDo.getCount());

                List<FbaProductDetailRes> productDetailResList = new ArrayList<>();
                LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getPackageId, packageDo.getId());
                List<FirstVesselOrderProductDo> firstVesselOrderProductDos = firstVesselOrderProductDao.selectList(productDoLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(firstVesselOrderProductDos)) {
                    firstVesselOrderProductDos.forEach(productDo -> {
                        FbaProductDetailRes productDetailRes = fbaProductService.detail(productDo.getProductId());
                        productDetailRes.setCount(productDo.getCount());
                        productDetailResList.add(productDetailRes);
                    });
                }

                packageDetailRes.setProductList(productDetailResList);
                packageDetailResList.add(packageDetailRes);
            });
        }
        res.setPackageList(packageDetailResList);

        List<FirstVesselPrice> priceList = new ArrayList<>();
        FirstVesselPrice deliveryFee = new FirstVesselPrice();
        deliveryFee.setPriceName("尾程派送费");
        deliveryFee.setPrice(entityDo.getDeliveryFee());
        priceList.add(deliveryFee);
        LambdaQueryWrapper<FirstVesselOrderPriceDo> priceDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        priceDoLambdaQueryWrapper.eq(FirstVesselOrderPriceDo::getOrderId, id);
        List<FirstVesselOrderPriceDo> firstVesselOrderPriceDos = firstVesselOrderPriceDao.selectList(priceDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(firstVesselOrderPriceDos)) {
            firstVesselOrderPriceDos.forEach(firstVesselOrderPriceDo -> {
                FirstVesselPrice price = new FirstVesselPrice();
                price.setPrice(firstVesselOrderPriceDo.getPrice());
                price.setPriceName(firstVesselOrderPriceDo.getPriceName());
                priceList.add(price);
            });
        }

        res.setPriceList(priceList);
        return res;
    }

    private String getResultStatusStr(Integer resultStatus) {
        if (resultStatus == null)
            return "";
        if (resultStatus == 1) {
            return "当前订单";
        } else if (resultStatus == 2) {
            return "已完成";
        } else if (resultStatus == 3) {
            return "已退回";
        }
        return "";
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<FirstVesselOrderPageRes> getList(Map<String, String> map) {
        QueryWrapper<FirstVesselOrderDo> wrapper = queryBuild(map);
        List<FirstVesselOrderDo> list = this.list(wrapper);
        List<FirstVesselOrderPageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<FirstVesselOrderDo> wrapper = queryBuild(map);
        IPage<FirstVesselOrderDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<FirstVesselOrderPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        result.setMapInfo(census(map));
        return result;
    }

    @Override
    public void setCostFee(FirstVesselPriceReq req, Long userId) {
        LambdaQueryWrapper<FirstVesselOrderPriceDo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(FirstVesselOrderPriceDo::getOrderId, req.getId());
        firstVesselOrderPriceDao.delete(wrapper);

        for (FirstVesselPrice firstVesselPrice : req.getPriceList()) {
//            if(firstVesselPrice.getPrice() == null){
//                throw new BizException("请填写金额");
//            }
            if (StringUtils.isBlank(firstVesselPrice.getPriceName())) {
                throw new BizException(SysConstant.Pls_Fill_ProjectName);
            }
            FirstVesselOrderPriceDo priceDo = new FirstVesselOrderPriceDo();
            priceDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            priceDo.setOrderId(req.getId());
            priceDo.setPriceName(firstVesselPrice.getPriceName());
            priceDo.setPrice(firstVesselPrice.getPrice());
            firstVesselOrderPriceDao.insert(priceDo);
        }
    }

    @Override
    public SingleResult setCostFeeInit(Long id) {
        FirstVesselPriceRes res = new FirstVesselPriceRes();
        res.setId(id);
        List<Map> priceList = new ArrayList<>();
        LambdaQueryWrapper<FirstVesselOrderPriceDo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(FirstVesselOrderPriceDo::getOrderId, id);
        List<FirstVesselOrderPriceDo> firstVesselOrderPriceDos = firstVesselOrderPriceDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(firstVesselOrderPriceDos)) {
            firstVesselOrderPriceDos.forEach(firstVesselOrderPriceDo -> {
                Map map = new HashMap();
                map.put("priceName", firstVesselOrderPriceDo.getPriceName());
                map.put("price", firstVesselOrderPriceDo.getPrice());
                priceList.add(map);
            });
        }
        res.setPriceList(priceList);
        return SingleResult.success(res);
    }

    @Override
    public List<FirstVesselExcelImportPackageRes> importExcel(MultipartFile file) throws IOException {
        if (file == null) {
            throw new BizException(SysConstant.Pls_Choose_File);
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!GlobalConstants.IMG_TYPE_XLS.equals(suffix.toUpperCase()) &&
                !GlobalConstants.IMG_TYPE_XLSX.equals(suffix.toUpperCase())) {
            throw new BizException(SysConstant.File_Form_Incorrect);
        }
        List<FIrstVesselExcelImportVo> excelImportVoList = ExcelUtils.importExcel(file, 0, 1, FIrstVesselExcelImportVo.class);
        List<FirstVesselExcelImportPackageRes> packageList = new ArrayList<>();
        Map<Long, List<FIrstVesselExcelImportVo>> map = excelImportVoList.stream().filter(product -> StringUtils.isNotBlank(product.getCommoditySku())).collect(Collectors.groupingBy(FIrstVesselExcelImportVo::getPackageNo));
        if (!CollectionUtils.isEmpty(map)) {
            for (Long packageNo : map.keySet()) {
                List<FIrstVesselExcelImportVo> excelImportVos = map.get(packageNo);
                if (!CollectionUtils.isEmpty(excelImportVos)) {
                    FirstVesselExcelImportPackageRes packageAdd = new FirstVesselExcelImportPackageRes();
                    packageAdd.setPackageHeight(excelImportVos.get(0).getHeight().floatValue());
                    packageAdd.setPackageLenght(excelImportVos.get(0).getLength().floatValue());
                    packageAdd.setPackageWidth(excelImportVos.get(0).getWidth().floatValue());
                    packageAdd.setPackageWeight(excelImportVos.get(0).getWeight().floatValue());
                    packageAdd.setPackageCount(excelImportVos.get(0).getPackageCount());
                    packageAdd.setPoNumber(excelImportVos.get(0).getPoNumber());
                    packageAdd.setUpcNumber(excelImportVos.get(0).getUpcNumber());
                    packageAdd.setTips(excelImportVos.get(0).getTips());

                    List<JSONObject> productAddList = new ArrayList<>();
                    for (FIrstVesselExcelImportVo excelImportVo : excelImportVos) {
                        //商品
                        JSONObject productAdd = new JSONObject();
                        LambdaQueryWrapper<ProductInfoDo> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(ProductInfoDo::getCommoditySku, excelImportVo.getCommoditySku());
                        ProductInfoDo productInfoDo = productInfoDao.selectOne(wrapper);
                        if (productInfoDo != null) {
                            productAdd.put("productId", productInfoDo.getId());
                            productAdd.put("commoditySku", productInfoDo.getCommoditySku());
                            productAdd.put("productName", productInfoDo.getCommodityName());
                            productAdd.put("createTime", productInfoDo.getCreateTime());
                        } else {
                            productAdd.put("productId", "");
                            productAdd.put("commoditySku", "产品不存在，请检查SKU");
                            productAdd.put("productName", "");
                            productAdd.put("createTime", "");
                        }
                        productAdd.put("count", excelImportVo.getCount());

                        productAddList.add(productAdd);
                    }

                    packageAdd.setProductDetailList(productAddList);

                    packageList.add(packageAdd);
                }
            }
        }

        return packageList;
    }

    //统计信息
    private Map census(Map<String, String> queryMap) {
        List<Map> result = new ArrayList<>();

        Map mapTotal = new HashMap();
        queryMap.remove("status");
        int total = dao.selectCount(queryBuild(queryMap));
        mapTotal.put("count", total);
        mapTotal.put("name", "全部");
        result.add(mapTotal);


        LambdaQueryWrapper<DicBusinessItemDo> businessItemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        businessItemDoLambdaQueryWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.seaTransportationStatus);
        List<DicBusinessItemDo> businessItemDoList = dicBusinessItemDao.selectList(businessItemDoLambdaQueryWrapper);

        if (!CollectionUtils.isEmpty(businessItemDoList)) {
            for (DicBusinessItemDo itemDo : businessItemDoList) {
                queryMap.put("status", itemDo.getId() + "");
                Map map = new HashMap();
                int count = dao.selectCount(queryBuild(queryMap));
                map.put("count", count);
                map.put("name", itemDo.getDicItemValue());
                map.put("id", itemDo.getId());
                result.add(map);
            }
        }


        Map map = new HashMap();
        map.put("census", result);
        return map;
    }

    //查询分页列表之后对列表数据的处理
    private List<FirstVesselOrderPageRes> handlerListAfter(List<FirstVesselOrderDo> list) {
        List<FirstVesselOrderPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(firstVesselOrderDo -> {
                FirstVesselOrderPageRes res = new FirstVesselOrderPageRes();
                res.setId(firstVesselOrderDo.getId());
                res.setFbaStorageId(firstVesselOrderDo.getFbaStorageId());
                res.setStorageId(firstVesselOrderDo.getStorageId());
                res.setOrderNumber(firstVesselOrderDo.getOrderNumber());
                res.setRemark(firstVesselOrderDo.getRemark());
                res.setCreateTime(firstVesselOrderDo.getCreateTime());
                res.setResultStatus(getResultStatusStr(firstVesselOrderDo.getResultStatus()));
                res.setIsLabelling(firstVesselOrderDo.getIsLabelling() == 1 ? "已贴标" : "未贴标");
                res.setIsLabel(firstVesselOrderDo.getIsLabelling());
                StorageDo storageDo = storageService.getBaseMapper().selectById(firstVesselOrderDo.getStorageId());
                if (storageDo != null) {
                    res.setStorage(storageDo.getStorageName());
                }
                FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(firstVesselOrderDo.getFbaStorageId());
                if (fbaStorageDo != null) {
                    res.setFbaStorage(fbaStorageDo.getFbaName());
                }
                res.setStatus(firstVesselOrderDo.getStatus());
                DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(firstVesselOrderDo.getStatus());
                if (businessItemDo != null) {
                    res.setStatusStr(businessItemDo.getDicItemValue());
                }
                businessItemDo = dicBusinessItemDao.selectById(firstVesselOrderDo.getLogisticsType());
                if (businessItemDo != null) {
                    res.setLogisticsType(businessItemDo.getDicItemValue());
                }
                CompanyDo companyDo = companyDao.selectById(firstVesselOrderDo.getCompanyId());
                if (companyDo != null) {
                    res.setCompanyCode(companyDo.getCompanyCode());
                }


                LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, firstVesselOrderDo.getId());
                List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(packageDoLambdaQueryWrapper);
                int packageCount = 0;
                int productCount = 0;
                double volume = 0;
                double weight = 0;
                if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
                    for (FirstVesselOrderPackageDo packageDo : firstVesselOrderPackageDos) {
                        packageCount += packageDo.getCount();
                        volume += packageDo.getCount() * packageDo.getLength() * packageDo.getWidth() * packageDo.getHeight() / 1000000;
                        weight += packageDo.getWeight() * packageDo.getCount();

                        LambdaQueryWrapper<FirstVesselOrderProductDo> productWrapper = new LambdaQueryWrapper<>();
                        productWrapper.eq(FirstVesselOrderProductDo::getPackageId, packageDo.getId());
                        List<FirstVesselOrderProductDo> firstVesselOrderProductDos = firstVesselOrderProductDao.selectList(productWrapper);
                        if (!CollectionUtils.isEmpty(firstVesselOrderProductDos)) {
                            productCount += firstVesselOrderProductDos.stream().mapToInt(FirstVesselOrderProductDo::getCount).sum() * packageDo.getCount();
                        }
                    }
                }
                res.setVolume(numberFormat(volume));
                res.setPackageCounts(packageCount);
                res.setWeight(weight);
                res.setProductCount(productCount);


                result.add(res);
            });
        }
        return result;
    }

    private IPage<FirstVesselOrderDo> pageInit(Map<String, String> map) {
        IPage<FirstVesselOrderDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<FirstVesselOrderDo> queryBuild(Map<String, String> map) {
        QueryWrapper<FirstVesselOrderDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("order_number", map.get("keyword"));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("company_id", map.get("companyId"));
        }
        if (StringUtils.isNotBlank(map.get("startDate"))) {
            wrapper.ge("create_time", map.get("startDate"));
        }
        if (StringUtils.isNotBlank(map.get("endDate"))) {
            wrapper.le("create_time", map.get("endDate"));
        }
        if (StringUtils.isNotBlank(map.get("isContainer"))) {
            wrapper.eq("is_container", map.get("isContainer"));
        }
        if (StringUtils.isNotBlank(map.get("storageId"))) {
            wrapper.eq("storage_id", map.get("storageId"));
        }
        if (StringUtils.isNotBlank(map.get("fbaStorageId"))) {
            wrapper.eq("fba_storage_id", map.get("fbaStorageId"));
        }


        return wrapper.orderByDesc("id");
    }


    private void handlerFee(FirstVesselOrderDo entityDo) {

        List<FirstVesselPriceVo> priceVoList = new ArrayList<>();

        LambdaQueryWrapper<DicBusinessItemDo> businessItemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        businessItemDoLambdaQueryWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.fbaOrderOutPutTruck);
        List<DicBusinessItemDo> businessItemDoList = dicBusinessItemDao.selectList(businessItemDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(businessItemDoList)) {
            for (DicBusinessItemDo businessItemDo : businessItemDoList) {
                LambdaQueryWrapper<FirstVesselOrderPackageDo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(FirstVesselOrderPackageDo::getOrderId, entityDo.getId());
                List<FirstVesselOrderPackageDo> packageDoList = firstVesselOrderPackageDao.selectList(wrapper);
                float totalPriceBySize = 0;
                float totalPriceByVolume = 0;

                //如果flag为true表示 有的包裹价格匹配不上，则 不展示该快递公司的 运算价格
                boolean sizeFlag = false;
                boolean volumeFlag = false;

                for (FirstVesselOrderPackageDo packageDo : packageDoList) {
                    double size = packageDo.getHeight() + packageDo.getWidth() + packageDo.getLength();
                    double volume = packageDo.getHeight() * packageDo.getWidth() * packageDo.getLength() * packageDo.getCount() / 1000000;
                    double weight = packageDo.getWeight();

                    //根据三边和计算
                    LambdaQueryWrapper<FbaDimensDo> fbaDimensDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    fbaDimensDoLambdaQueryWrapper.ge(FbaDimensDo::getSize, size)
                            .ge(FbaDimensDo::getWeight, weight)
                            .eq(FbaDimensDo::getType, 1)
                            .eq(FbaDimensDo::getStorageId, entityDo.getStorageId())
                            .eq(FbaDimensDo::getTrackId, businessItemDo.getId())
                            .orderByAsc(FbaDimensDo::getSize).last("limit 1");

                    FbaDimensDo fbaDimensDo = fbaDimensDao.selectOne(fbaDimensDoLambdaQueryWrapper);
                    if (fbaDimensDo != null) {
                        LambdaQueryWrapper<FbaShipPriceDo> fbaShipPriceDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        fbaShipPriceDoLambdaQueryWrapper.eq(FbaShipPriceDo::getDimensId, fbaDimensDo.getId())
                                .eq(FbaShipPriceDo::getFbaStorageId, entityDo.getFbaStorageId())
                                .eq(FbaShipPriceDo::getActive, 1);

                        FbaShipPriceDo fbaShipPriceDo = fbaShipPriceDao.selectOne(fbaShipPriceDoLambdaQueryWrapper);
                        if (fbaShipPriceDo != null) {
                            totalPriceBySize += fbaShipPriceDo.getPrice() * packageDo.getCount();
                        } else {
                            sizeFlag = true;
                        }
                    } else {
                        sizeFlag = true;
                    }


                    //根据体积计算
                    LambdaQueryWrapper<FbaDimensDo> fbaDimensDoLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                    fbaDimensDoLambdaQueryWrapper2.ge(FbaDimensDo::getSize, volume)
                            .ge(FbaDimensDo::getWeight, weight)
                            .eq(FbaDimensDo::getType, 2)
                            .eq(FbaDimensDo::getStorageId, entityDo.getStorageId())
                            .eq(FbaDimensDo::getTrackId, businessItemDo.getId())
                            .orderByAsc(FbaDimensDo::getSize).last("limit 1");

                    FbaDimensDo fbaDimensDo2 = fbaDimensDao.selectOne(fbaDimensDoLambdaQueryWrapper2);
                    if (fbaDimensDo2 != null) {
                        LambdaQueryWrapper<FbaShipPriceDo> fbaShipPriceDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        fbaShipPriceDoLambdaQueryWrapper.eq(FbaShipPriceDo::getDimensId, fbaDimensDo2.getId())
                                .eq(FbaShipPriceDo::getFbaStorageId, entityDo.getFbaStorageId())
                                .eq(FbaShipPriceDo::getActive, 1);

//                        FbaShipPriceDo fbaShipPriceDo = fbaShipPriceDao.selectList(fbaShipPriceDoLambdaQueryWrapper).get(0);
                        FbaShipPriceDo fbaShipPriceDo = fbaShipPriceDao.selectOne(fbaShipPriceDoLambdaQueryWrapper);
                        if (fbaShipPriceDo != null) {
                            totalPriceByVolume += fbaShipPriceDo.getPrice();
                        } else {
                            volumeFlag = true;
                        }
                    } else {
                        volumeFlag = true;
                    }

                }

                if (!sizeFlag) {
                    FirstVesselPriceVo firstVesselPriceVo = new FirstVesselPriceVo();
                    firstVesselPriceVo.setTrackId(businessItemDo.getId());
                    firstVesselPriceVo.setPrice(totalPriceBySize);
                    priceVoList.add(firstVesselPriceVo);
                }

                if (!volumeFlag) {
                    FirstVesselPriceVo firstVesselPriceVo = new FirstVesselPriceVo();
                    firstVesselPriceVo.setTrackId(businessItemDo.getId());
                    firstVesselPriceVo.setPrice(totalPriceByVolume);
                    priceVoList.add(firstVesselPriceVo);
                }
            }
        }

        FirstVesselPriceVo priceVo = null;
        if (!CollectionUtils.isEmpty(priceVoList)) {
            priceVo = priceVoList.stream().distinct().sorted(Comparator.comparing(FirstVesselPriceVo::getPrice)).limit(1).collect(Collectors.toList()).get(0);
            entityDo.setDeliveryFee(priceVo.getPrice());
            entityDo.setTrackId(priceVo.getTrackId());
            dao.updateById(entityDo);
        }

//        float totalReportPrice = 0; //总的物资价格
//        LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getOrderId, entityDo.getId());
//        List<FirstVesselOrderProductDo> firstVesselOrderProductDos = firstVesselOrderProductDao.selectList(productDoLambdaQueryWrapper);
//        if (!CollectionUtils.isEmpty(firstVesselOrderProductDos)) {
//            for (FirstVesselOrderProductDo orderProductDo : firstVesselOrderProductDos) {
//                ProductInfoDo productInfoDo = productInfoDao.selectById(orderProductDo.getProductId());
//                if (productInfoDo != null) {
//                    totalReportPrice += orderProductDo.getCount() * productInfoDo.getReportPrice();
//                }
//            }
//        }
//
//
//        // 计算清关费 比例为 10% * 总物值
//        entityDo.setClearanceFee(totalReportPrice * 0.1F);
//
//        //计算关税 一定比例 * 总物值
//        entityDo.setTariffFee((float) (totalReportPrice * (entityDo.getTariffFeePercentage() / 100)));


    }

    private double numberFormat(double f) {
        BigDecimal b = new BigDecimal(f);
        return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
